package com.hbisedm.interninfosys.intern.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbisedm.interninfosys.intern.entity.JdUser;
import com.hbisedm.interninfosys.intern.entity.LoginUser;
import com.hbisedm.interninfosys.intern.entity.Role;
import com.hbisedm.interninfosys.intern.entity.User;
import com.hbisedm.interninfosys.intern.mapper.RoleMapper;
import com.hbisedm.interninfosys.intern.mapper.UserMapper;
import com.hbisedm.interninfosys.intern.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Sam
 * @since 2020-12-04
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {

    @Resource
    RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("username", s);
        User user = getOne(qw);
        if(user == null) {
            //避免返回null，这里返回一个不含有任何值的User对象，在后期的密码比对过程中一样会验证失败
            return new LoginUser();
        }
        //查询用户的角色信息，并返回存入user中
        List<Role> roles = roleMapper.getRolesByUid(user.getUsername());
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user, loginUser);
        loginUser.setRole(roles);
        return loginUser;
    }
}
